const _ = require('lodash');
const foodItemFacade = require('../../app/facade/foodItem.server.facade.js');
module.exports = {
    getFoodItems : getFoodItems,
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    getFoodItemByNameAndProducer:getFoodItemByNameAndProducer,
    addFoodItem:addFoodItem,
    deleteFoodByItemId:deleteFoodByItemId
}

function getFoodItemByName(req, res, next) {
    let params = req.params;
    let name = params.name;
    if (_.isEmpty(name)) {
        return next(new Error('food name is empty'));
    } else {
    foodItemFacade.getFoodItemByName(name, (error, result) => {
        if (error) {
            return next(new Error(error));
        } else {
            return res.json(result);
        }
    });
    }
}

function getFoodItems(req,res,next){
    foodItemFacade.getFoodItems((error,result)=>{
        if (error) {
            return next(new Error(error));
        } else {
            //return res.json(result);
            // res.render('foodItem', result);
            return res.json(result);
        }
    })
}

function getFoodItemByProducer(req, res, next) {
    let body = req.body;
    let producer = body.producer;
    if (_.isEmpty(producer)) {
        return next(new Error('producer name is empty'));
    } else {
    foodItemFacade.getFoodItemByProducer(producer, (error, result) => {
        if (error) {
            return next(new Error(error));
        } else {
            return res.json(result);
        }
    });
    }
}

function getFoodItemByNameAndProducer(req,res,next){
    let body = req.body;
    let name = body.name;
    let producer = body.producer;
    if (_.isEmpty(name)) {
        return next(new Error('food name is empty'));
    }
    if (_.isEmpty(producer)) {
        return next(new Error('producer name is empty'));
    }
    foodItemFacade.getFoodItemByNameAndProducer(name,producer, (error, result) => {
        if (error) {
            return next(new Error(error));
        } else {
            return res.json(result);
        }
    });
}

function addFoodItem(req,res,next){
    let body = req.body;
    let item = body;
    if(_.isEmpty(item)){
        return next(new Error("food item is empty"));
    }
    foodItemFacade.addFoodItem(item,(error,result)=>{
        if (error) {
            return next(new Error(error));
        } else {
            return res.json(result);
        }
    });
}

function deleteFoodByItemId(req,res,next){
    let params = req.params;
    let itemId = params.itemId;
    if(_.isEmpty(itemId)){
        return next(new Error("item id is empty"));
    }
    foodItemFacade.deleteFoodByItemId(itemId,(error,result)=>{
        if(error){
            return next(new Error(error));
        }else{
            return res.json(result);
        }
    })
}